<!DOCTYPE html>

<style>
  input {
    width: 400px;
    border: #f1f1f1 solid 1px;
    border-radius: 3px;
    padding: 8px 15px;
  }
  button {
    padding: 7px 15px;
    border-radius: 3px;
    background: #1a73e8;
    color: #fff;
    border: 0;
  }
</style>

<div id="demo1">
  <h3>普通字符串形式</h3>
  <input placeholder="输入你想问的问题" />
  <button>提问</button>
</div>

<div id="demo2">
  <h3>通过JSON发送数据</h3>
  <form>
    <input name="name" placeholder="输入姓名" />
    <input name="age" placeholder="输入年龄" type="number" />
    <button>提交</button>
  </form>
</div>

<div id="demo3">
  <h3>通过x-www-form-urlencoded发送数据</h3>
  <form>
    <input name="name" placeholder="输入姓名" />
    <input name="age" placeholder="输入年龄" type="number" />
    <button>提交</button>
  </form>
</div>

<div id="demo4">
  <h3>通过multipart/form-data发送文件</h3>
  <form>
    <input name="name" placeholder="输入姓名" />
    <input name="age" placeholder="输入年龄" type="number" />
    <input name="photo" type="file" />
    <button>提交</button>
  </form>
</div>

<script src="http://localhost:9000/sdk.js"></script>

<script>
  document.querySelector('#demo1 button').addEventListener('click', () => {
    const text = document.querySelector('#demo1 input').value
    ScopedRequest.run(`
      get "http://api.qingyunke.com/api.php?key=free&appid=0&msg=${text}" -> {
        content
      }
    `).then(({ content }) => {
      alert(content.replace(/\{br\}/g, '\n'))
    });
  });
</script>

<script>
  document.querySelector('#demo2 form').addEventListener('submit', (e) => {
    e.preventDefault();
    const form = e.target;
    const formdata = new FormData(form);
    const data = {};
    for (let [key, value] of formdata) {
      data[key] = value;
    }
    ScopedRequest.run(
      `
        post "/api" + { name } -> { id, name }
      `,
      null,
      [data],
    );
  })
</script>

<script>
  document.querySelector('#demo3 form').addEventListener('submit', (e) => {
    e.preventDefault();
    const form = e.target;
    const formdata = new FormData(form);
    const data = {};
    for (let [key, value] of formdata) {
      data[key] = value;
    }
    ScopedRequest.createRequest('application/x-www-form-urlencoded')
      .run(
        `
          post "/api" + { name } -> { id }
        `,
        null,
        [data],
      );
  })
</script>

<script>
  document.querySelector('#demo4 form').addEventListener('submit', (e) => {
    e.preventDefault();
    const form = e.target;
    const formdata = new FormData(form);
    const data = {};
    for (let [key, value] of formdata) {
      data[key] = value;
    }
    ScopedRequest.createRequest('multipart/form-data')
      .run(
        `
          post "/api" + { name, photo } -> { id, files }
        `,
        null,
        [data],
      );
  })
</script>
